<?php
use app\assets\PublishAsset;
use yii\helpers\Html;
use yii\helpers\Url;

PublishAsset::register($this);
?>

<style>
    .datagrid-row-editing .datagrid-cell {
        overflow: visible !important;
    }
</style>

<div id="postageTempalteForm">
    <div class="form-group">
        <div id="postageTemplateToolbox" class="form-group col-md-8" style="padding-left: 0; padding-right: 0;">
            <div class="col-md-9 col-sm-9" style="padding-left: 0;">
                <select id="postageTemplates" class="form-control" >
                </select>
            </div>

            <div class="col-md-1 col-sm-1" >
                <button class="btn btn-default" id="editTemplateBtn" type="button">保存</button>
            </div>

            <div class="col-md-1 col-sm-1" >
                <button class="btn btn-default" id="deleteTemplateBtn" type="button">删除</button>
            </div>

            <div class="col-md-1 col-sm-1" style="padding: 0;">
                <p class="btn" id="showAddPostageTemplateModalBtn"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></p>
            </div>
        </div>
        <div>
            <div id="postageTemplateDetail">
                <table id="postageTemplateDetailTable">
                </table>
                <div class="col-md-4" style="margin:10px 70px; float: right;">
                    <a href="javascript:void(0)" class=" btn btn-primary" onclick="insert()">插入</a>
                </div>
                <div style="clear:both"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade modal-xs" id="addPostageTemplateModal" tabindex="-1"
     role="dialog" aria-labelledby="mySmallModalLabel"><div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title" id="myModalLabel">请输入新增模板名称</h4>
        </div>
        <div class="modal-body" id="tipDialog">
            <input type="text" class="form-control" id="templateName"/>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary" id="addNewTemplateBtn">确定</button>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function(){
        //加载模板
        $.ajax({
            url:"get-all",
            dataType: "json",
            async: false,
            success: function (data) {
                $('#postageTemplates').empty();
                $.each(data,function(){
                    $('#postageTemplates').append('<option value="'+this['id']+'" data-default-unit-price='
                        + this['default_unit_price'] +'>'+this['name']+'</option>');
                });
            }
        });
        //显示表格
        setTimeout(function() {
            $('#postageTemplateDetailTable').datagrid({
                title:'模板详情',
                iconCls:'icon-edit',
                width:$('#postageTemplateToolbox').outerWidth(true),
                height:600,
                singleSelect:true,
                showFooter:true,
                idField:'province_name',
                url:'get-detail',
                columns:[[
                    {field:'province_name',title:'省份',align:'center',width:$('#postageTemplateToolbox').outerWidth(true) / 3,
                        formatter:function(value,row,index) {
                            if (row.editing && value != '全国'){
                                var select = '<select class="selectpicker" multiple data-live-search="true" data-size="10" data-none-selected-text="">';
                                var loadedData = $('#postageTemplateDetailTable').datagrid('getData');
                                var selectedProvinces = [];
                                for (var i = 0; i < loadedData.rows.length; i++) {
                                    if (i == index) continue;
                                    selectedProvinces = selectedProvinces.concat(loadedData.rows[i].province_name.split(', '));
                                }
                                $.each(provinces, function(){
                                    var isSelected = value.split(', ').indexOf(this['name']) != -1;
                                    var isRemoved = selectedProvinces.indexOf(this['name']) != -1;
                                    if (!isRemoved) {
                                        select = select + '<option';
                                        if (isSelected) {
                                            select = select + ' selected="' + isSelected + '"';
                                        }
                                        select = select + '>' + this['name'] + '</option>';
                                    }
                                });
                                select = select + '</select>';
                                return select;
                            } else {
                                return value;
                            }
                        }
                    },
                    {field:'unit_price',title:'单价',align:'center',editor:{type:'numberbox',options:{precision:2}},width:$('#postageTemplateToolbox').outerWidth(true) / 3},
                    {field:'action',title:'操作',align:'center', width:$('#postageTemplateToolbox').outerWidth(true) / 3 - 2,
                        formatter:function(value,row,index){
                            if (row.editing){
                                var s = '<a href="javascript:void(0)" onclick="saverow(this)">保存</a> ';
                                var c = '<a href="javascript:void(0)" onclick="cancelrow(this)">取消</a>';
                                return s+c;
                            } else {
                                var e = '<a href="javascript:void(0)" onclick="editrow(this)">编辑</a> ';
                                var d = '';
                                if (row.province_name != '全国' ) {
                                    var d = '<a href="javascript:void(0)" onclick="deleterow(this)">删除</a>';
                                }
                                return e+d;
                            }
                        }
                    }
                ]],
                onEndEdit:function(index,row){
                    var select = $('.datagrid-row-selected').find('.filter-option.pull-left');
                    if (select.length > 0) {
                        row.province_name = select.text();
                    }
                },
                onBeforeEdit:function(index,row){
                    row.editing = true;
                    $(this).datagrid('refreshRow', index);
                },
                onAfterEdit:function(index,row){
                    if (row.province_name == null || row.province_name == "") {
                        alert('请选择省份')
                        $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                    } else {
                        row.editing = false;
                        $(this).datagrid('refreshRow', index);
                    }
                },
                onBeginEdit:function(index,row){
                    $('.selectpicker').selectpicker('render');
                },
                onCancelEdit:function(index,row){
                    if (row.province_name == null || row.province_name == "") {
                        alert('请选择省份')
                        $('#postageTemplateDetailTable').datagrid('beginEdit', index);
                    } else {
                        row.editing = false;
                        $(this).datagrid('refreshRow', index);
                    }
                },
                onLoadSuccess:function(data){
                    var unit_price = $($('#postageTemplates')[0].options[$('#postageTemplates')[0].selectedIndex]).attr('data-default-unit-price');
                    if (unit_price) {
                        insert({"province_name":"全国","unit_price":unit_price});
                        $('#postageTemplateDetailTable').datagrid('endEdit', $('#postageTemplateDetailTable').datagrid('getRowIndex',
                            $('#postageTemplateDetailTable').datagrid('getSelected')));
                    }
                }
            });
            reload();
        }, 300);

        $('body').on('click', '#showAddPostageTemplateModalBtn', function(){
            $('#addPostageTemplateModal').modal();
            $("#templateName").val('');
            //设置提示框的css样式(居中展示)
            setTimeout(function() {
                $("#addPostageTemplateModal").find('.modal-content').css({
                    "width": function() {
                        return 430;
                    },
                    "margin-top": function () {
                        return (($(window).height() - $(this).height()) / 2 );
                    },
                    "margin-left": function () {
                        return (($(window).width() - $(this).width()) / 2 );
                    },
                });
            }, 200);
        })

        $('body').on('click','#addNewTemplateBtn',function(){
            //为空不操作
            if(!$("#templateName").val()){
                alert('请输入新增模板名称');
                return;
            }

            $.ajax({
                url: "add",
                data:{"name":$("#templateName").val()},
                dataType: "json",
                type: 'POST',
                success: function (data) {
                    if(data===0) {
                        alert('填写信息有误,请检查');
                    } else {
                        $('#postageTemplates').append('<option value="'+data['id']+'" data-default-unit-price="'
                            + data['default_unit_price'] +'">'+data['name']+'</option>');
                        $('#postageTemplates option:last').attr('selected', true);
                        reload();
                        $("#templateName").val('');
                        $('#addPostageTemplateModal').modal('hide');
                    }
                }
            });
        });

        $('body').on('click','#deleteTemplateBtn',function(){
            //为空不操作
            if(!$("#postageTemplates").val()){
                return;
            }

            $.ajax({
                url: "delete",
                data:{"id":$("#postageTemplates").val()},
                dataType: "json",
                type: 'POST',
                success: function (data) {
                    if(data.status == 'success') {
                        document.getElementById('postageTemplates').options.remove(
                            document.getElementById('postageTemplates').selectedIndex)
                        reload();
                    }else {
                        alert('删除失败: ' + data.message);
                    }
                }
            });
        });

        $('body').on('click','#editTemplateBtn',function(){
            //为空不操作
            if(!$("#postageTemplates").val()){
                return;
            }

            $.ajax({
                url: "edit",
                data:{
                    "id":$("#postageTemplates").val(),
                    "insertData":
                        $('#postageTemplateDetailTable').datagrid('getChanges', 'inserted').concat(
                            $('#postageTemplateDetailTable').datagrid('getChanges', 'updated')),
                    "deleteData":$('#postageTemplateDetailTable').datagrid('getChanges', 'deleted'),
                },
                dataType: "json",
                type: 'POST',
                success: function (data) {
                    if(data.status == "failed") {
                        alert(data.message);
                    }
                    $.each($('#postageTemplateDetailTable').datagrid('getRows'),function(){
                        if (this["province_name"] == '全国') {
                            var unit_price = this["unit_price"];
                            $($('#postageTemplates')[0].options[$('#postageTemplates')[0].selectedIndex]).attr('data-default-unit-price', unit_price);
                            return false;
                        }
                    });
                    reload();
                }
            });
        });

        $('body').on('change', '#postageTemplates', function(){
            reload();
        });

        var provinces = [
        ]

        $.ajax({
            url: "get-all-province",
            data:{},
            dataType: "json",
            type: 'POST',
            async:false,
            success: function (data) {
                if(data) {
                    provinces = data;
                }
            }
        });

        window.onbeforeunload=function() {
            if ($('#postageTemplateDetailTable').datagrid('getChanges').length > 0) {
                return '有未保存的修改,请点击"保存"保存修改';
            }
        } ;
    });

    function getRowIndex(target){
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }
    function editrow(target){
        $('#postageTemplateDetailTable').datagrid('beginEdit', getRowIndex(target));
    }
    function deleterow(target){
        $.messager.confirm('Confirm','Are you sure?',function(r){
            if (r){
                $('#postageTemplateDetailTable').datagrid('deleteRow', getRowIndex(target));
            }
        });
    }
    function saverow(target){
        $('#postageTemplateDetailTable').datagrid('endEdit', getRowIndex(target));
    }
    function cancelrow(target){
        $('#postageTemplateDetailTable').datagrid('cancelEdit', getRowIndex(target));
    }
    function insert(target){
        index = 0;
        if (!target) {
            target = {
                "province_name" : "",
                "unit_price": "0.00"
            };
            index = $('#postageTemplateDetailTable').datagrid('getRows').length;
        }
            $('#postageTemplateDetailTable').datagrid('insertRow', {
                index:index,
            row:target
        });
        $('#postageTemplateDetailTable').datagrid('selectRow',index);
        $('#postageTemplateDetailTable').datagrid('beginEdit',index);
    }
    function reload(){
        $('#postageTemplateDetailTable').datagrid('options').queryParams = {
            "template_id" :$("#postageTemplates").val()
        };
        $('#postageTemplateDetailTable').datagrid('reload');
    }
</script>
